package kr.pe.dothome.yyar.myphone.controller;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import kr.pe.dothome.yyar.myphone.domain.MissedMessage;
import kr.pe.dothome.yyar.myphone.domain.Request;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;

public class MissedMessageSendingTask extends AsyncTask<Request, Void, Boolean> {
	private Context mContext;

	public MissedMessageSendingTask (Context context) {
		this.mContext = context;
	}
	
	@Override
	protected Boolean doInBackground(Request... params) {
		boolean result = true;
		try {
			Request req = params[0];
			for (MissedMessage msg : req.getMessageList()) {
				if(!sendMessage(msg)) {
					result = false;
					break;
				}
			}
			if(result)
				result = updateRequestState(req.getRequestId());
		} catch (Exception e) {
			result = false;
		}

		return result;
	}

	private boolean sendMessage(MissedMessage msg) throws Exception {
		URL url = new URL(
				"http://yyar.dothome.co.kr/myphone/insert_message_data.php"); // URL

		HttpURLConnection http = (HttpURLConnection) url.openConnection();

		http.setDefaultUseCaches(false);
		http.setDoInput(true);
		http.setDoOutput(true);
		http.setRequestMethod("POST");

		http.setRequestProperty("content-type",
				"application/x-www-form-urlencoded");


		OutputStreamWriter outStream = new OutputStreamWriter(
				http.getOutputStream(), "EUC-KR");
		PrintWriter writer = new PrintWriter(outStream);
		writer.write(msg.getPostQuery());
		writer.flush();

		InputStreamReader tmp = new InputStreamReader(
				http.getInputStream(), "EUC-KR");
		BufferedReader reader = new BufferedReader(tmp);
		
		StringBuilder builder = new StringBuilder();
		String str;
		while ((str = reader.readLine()) != null) {
			builder.append(str + "\n");
		}
		return !builder.toString().contains("NO");
	}

	private boolean updateRequestState(String rid) throws Exception {
		URL url = new URL(
				"http://yyar.dothome.co.kr/myphone/update_request.php"); // URL

		HttpURLConnection http = (HttpURLConnection) url.openConnection();

		http.setDefaultUseCaches(false);
		http.setDoInput(true);
		http.setDoOutput(true);
		http.setRequestMethod("POST");

		http.setRequestProperty("content-type",
				"application/x-www-form-urlencoded");


		OutputStreamWriter outStream = new OutputStreamWriter(
				http.getOutputStream(), "EUC-KR");
		PrintWriter writer = new PrintWriter(outStream);
		writer.write("rid="+rid);
		writer.flush();

		InputStreamReader tmp = new InputStreamReader(
				http.getInputStream(), "EUC-KR");
		BufferedReader reader = new BufferedReader(tmp);
		
		StringBuilder builder = new StringBuilder();
		String str;
		while ((str = reader.readLine()) != null) {
			builder.append(str + "\n");
		}
		return !builder.toString().contains("ERROR");
	}

	@Override
	protected void onPostExecute(Boolean result) {
		super.onPostExecute(result);
		String msg = null;
		if(result)
			msg = "Sending Completed";
		else 
			msg = "Sending Failed";
		
		Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show(); 
	}
}
